<!--
 * @Author: wangjian
 * 656876071@qq.com
 * @Date: 2024-09-20 10:59:40
 * @LastEditTime: 2024-09-20 11:42:56
 * @FilePath: src/views/sys/user/UserRoleForm.vue
 * @Description: 
 -->
<script setup lang="ts">
import sysRoleApi, {type SysRole} from "@/views/sys/api/SysRoleApi";
import sysUserRoleApi, {type SysUserRole} from "@/views/sys/api/SysUserRoleApi";
import {reactive, ref} from "vue";
import {message} from "ant-design-vue";

const formData = reactive({
  userId: '',
  targetKeys: [] as string[],
  selectedKeys:[] as string[],
  roleData: [] as SysRole[],
  reset: (userId:string) => {
    formData.userId = userId
    formData.targetKeys = []
    formData.selectedKeys = []
    formData.roleData = []
  }
})
const {listAllRoles} = sysRoleApi()
const {getUserRoleIds, updateUserRoles} = sysUserRoleApi()
const modalIsVisible = ref(false)
const modalIsSubmitting = ref(false)

const showForm = (userId: string) => {
  modalIsSubmitting.value = false
  formData.reset(userId)
  listAllRoles().then(res => {
    formData.roleData = res.data
    return getUserRoleIds(userId)
  }).then(res => {
    formData.targetKeys = res.data
    modalIsVisible.value = true
  }).catch(e=>{
    message.error("查询基本信息失败")
  })
}

const modalSubmit = () => {
  let rawObject: SysUserRole = {
    userId: formData.userId,
    roleIds: formData.targetKeys
  }
  modalIsSubmitting.value = true
  updateUserRoles(rawObject).then(res => {
    if(res.code !== -1){
      message.success("保存成功")
      modalIsVisible.value = false
    }else{
      message.error(res.msg)
      modalIsSubmitting.value = false
    }
  })
}

const render = (item: SysRole) => {
  return item.roleName
}
const rowKey = (item: SysRole) => {
  return item.roleId
}

defineExpose({
  showForm
})

</script>

<template>
  <a-modal v-model:open="modalIsVisible" title="用户维护" width="50rem" :maskClosable="false">
    <a-form :disabled="modalIsSubmitting" :label-col="{span:5}" :wrapper-col="{span: 18}" label-align="right">
      <a-form-item label="角色列表">
        <a-transfer
            v-model:target-keys="formData.targetKeys"
            v-model:selected-keys="formData.selectedKeys"
            :data-source="formData.roleData"
            :titles="['可选角色', '已选角色']"
            :render="render"
            :rowKey="rowKey"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button key="back" @click="modalIsVisible = false">取消</a-button>
      <a-button :loading="modalIsSubmitting" key="submit" type="primary" @click="modalSubmit">保存</a-button>
    </template>
  </a-modal>
</template>

<style scoped>

</style>